package com.yjd.merchant.app.api.project;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yjd.comm.base.control.MerchantBaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.PagerModel;
import com.yjd.comm.merchant.dto.ProjectSummaryInfoDto;
import com.yjd.comm.project.model.PrjCategoryModel;
import com.yjd.comm.project.model.ProjectModel;
import com.yjd.comm.project.model.ProjectRateModel;
import com.yjd.comm.project.service.IPrjCategoryService;
import com.yjd.comm.project.service.IProjectService;
import com.yjd.comm.system.util.SysParamUtil;
import com.yjd.comm.util.ArithUtil;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.StringUtil;
import com.yjd.comm.vo.Constant;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.*;

/**
 * 商户APP 项目操作
 * Created by yangchangyan on 2017/11/28.
 */
@Controller("com.yjd.merchant.app.api.project.ProjectControl")
@Scope("prototype")
@RequestMapping("/merchant/project")
public class ProjectControl extends MerchantBaseControl {

    @Resource
    private IPrjCategoryService prjCategoryService;

    @Resource
    private IProjectService projectService;

    /**
     * 商品列表
     *
     * @param category_id 项目分类id（0 全部）
     * @param is_used 商品售卖状态 0：待售中(没有启用) 1：在售中（启用） 2：全部商品
     * @return
     * @throws
     */
    @RequestMapping(value = "/list")
    public void projectList(Long category_id, Integer is_used) throws Exception{

        Map<String, Object> paramMap = FrameUtil.newHashMap();
        paramMap.put("org_id", super.getMerchantSession().getOrg_id());
        if(null != category_id && category_id.intValue() != 0){
            paramMap.put("category_id", category_id);
        }
        if(null != is_used && is_used.intValue() != 2){
            // 是否启用 0否 1是
            paramMap.put("is_used", is_used);
        }
        paramMap.put("sort", "create_time desc");
        paramMap.put("rows", "10");

        List<ProjectSummaryInfoDto> projectSummaryInfoDtos = new ArrayList<ProjectSummaryInfoDto>();
        PagerModel projectPage = this.projectService.getPageModel(paramMap, DbWREnums.READ);
        List<ProjectModel> projects = projectPage.getDataList();
        if(null != projects && projects.size() > 0){
            ProjectSummaryInfoDto infoDto = null;
            for(ProjectModel p : projects){
                infoDto = new ProjectSummaryInfoDto();
                infoDto.setProject_id(p.getProject_id());
                infoDto.setAct_price(p.getAct_price());
                infoDto.setIs_used(p.getIs_used());
                infoDto.setProject_name(p.getProject_name());
                projectSummaryInfoDtos.add(infoDto);
            }
        }

        this.successData(FrameUtil.newHashMap("projectSummaryInfo", projectSummaryInfoDtos));
    }

    /**
     * 商品编辑
     *
     * @param project_id 项目id
     * @param
     * @return
     * @throws
     */
    @RequestMapping(value = "/edit")
    public void projectEditInfo(Long project_id) throws Exception{
        ProjectModel project = this.projectService.getModelById(project_id, DbWREnums.READ);
        if(null == project){
            this.errorMsg("商品不存在");
            return;
        }

        Long org_id = super.getMerchantSession().getOrg_id();
        if(org_id.longValue() != project.getOrg_id().longValue()){
            this.errorMsg("不可编辑");
            return;
        }

        ProjectSummaryInfoDto infoDto = new ProjectSummaryInfoDto();
        infoDto.setProject_id(project.getProject_id());
        infoDto.setAct_price(project.getAct_price());
        infoDto.setIs_used(project.getIs_used());
        infoDto.setProject_name(project.getProject_name());
        infoDto.setProject_price(project.getProject_price());
        infoDto.setPayment(project.getPayment());
        infoDto.setLoan_price(project.getLoan_price());
        infoDto.setCategoryName("");
        infoDto.setRateList(Collections.EMPTY_LIST);
        if(StringUtil.isNotEmpty(project.getRate_config())){
            Map<Integer, Double> currentRateConfig = JSON.parseObject(project.getRate_config(), new TypeReference<Map<Integer, Double>>(){});
            List<ProjectRateModel> projectRates = new ArrayList<ProjectRateModel>();
            ProjectRateModel rateModel = null;
            for(Integer limit : currentRateConfig.keySet()){
                rateModel = new ProjectRateModel();
                rateModel.setLimit(limit);
                rateModel.setRate(currentRateConfig.get(limit));
                projectRates.add(rateModel);
            }
            infoDto.setRateList(projectRates);
        }
        infoDto.setIs_used(project.getIs_used());

        PrjCategoryModel categoryModel = prjCategoryService.getModelById(project.getCategory_id(), DbWREnums.READ);
        if(null != categoryModel){
            infoDto.setCategoryName(categoryModel.getName());
        }

        this.successData(FrameUtil.newHashMap("projectSummaryInfo", infoDto));
    }

    /**
     * 商品编辑保存
     *
     * @param info 编辑后的商品信息
     * @param
     * @return
     * @throws
     */
    @RequestMapping(value = "/edit/submit")
    public void projectEditSubmit(ProjectSummaryInfoDto info) throws Exception{
        if(     null == info
                || null == info.getProject_price()
                || null == info.getAct_price()
                || null == info.getPayment()
                || null == info.getRateList()
                || 0 == info.getRateList().size()
                || info.getProject_price() < 0
                || info.getAct_price() < 0
                || info.getPayment() < 0){
            this.errorMsg("信息不正确，请重新检查。");
            return;
        }

        // 是否上架 0否 1是 （不为1则置为0，防止其他数据上传）
        if(1 != info.getIs_used().intValue()){
            info.setIs_used(0);
        }

        // 检查价格是否正确
        info.setLoan_price(ArithUtil.sub(info.getAct_price(), info.getPayment()));
        if(info.getLoan_price() < 0){
            this.errorMsg("价格信息不正确，请重新检查。");
            return;
        }

        // 检查期数是否正确
        String defaultPeriod = SysParamUtil.getValue(Constant.SysParamKeyEnum.MFQ_PERIODS_CONFIG);
        List<Integer> periodsList = StringUtil.getObject(defaultPeriod, List.class);
        Map latestRateConfig = new HashMap();
        for(ProjectRateModel rateConfigModel : info.getRateList()){
            if(periodsList.contains(rateConfigModel.getLimit())){
                latestRateConfig.put(rateConfigModel.getLimit().toString(), rateConfigModel.getRate().toString());
                continue;
            }

            this.errorMsg("分期信息不正确，请重新检查。");
            return;
        }

        // 更新项目信息
        ProjectModel projectModel = projectService.getModelById(info.getProject_id(), DbWREnums.READ);
        ProjectModel updateProject = new ProjectModel();
        updateProject.setProject_id(projectModel.getProject_id());
        updateProject.setWhere_version(projectModel.getVersion());
        updateProject.setProject_price(info.getProject_price());
        updateProject.setAct_price(info.getAct_price());
        updateProject.setPayment(info.getPayment());
        updateProject.setLoan_price(info.getLoan_price());
        updateProject.setIs_used(info.getIs_used());
        updateProject.setRate_config(JSON.toJSONString(latestRateConfig));
        projectService.update(updateProject);

        this.successMsg("修改成功");
    }

    /**
     * 项目分类列表
     *
     * @throws
     */
    @RequestMapping(value = "/category")
    public void projectCategory() throws Exception {
        List<PrjCategoryModel> projectCgy = prjCategoryService.getModelList(FrameUtil.newHashMap("is_used", "1"), DbWREnums.READ);
        PrjCategoryModel first = new PrjCategoryModel();
        first.setId(0L);
        first.setName("全部");
        projectCgy.add(0, first);
        this.successData(FrameUtil.newHashMap("cgyList", projectCgy));
    }

}
